package com.kingyea.mobilepolice.systemsync;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author cxc
 * @version v1.0.0
 * @description This is a class
 * @date Created in 2018.04.20 17:07
 */

public class ActiveMqUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ActiveMqUtils.class);

    public static List<Object> getInvokeMethodList(String username, String password, String brokerUrl, String subject) {
        Connection connection = null;
        try {
            //初始化ConnectionFactory
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(username, password, brokerUrl);
            //创建mq连接
            connection = connectionFactory.createConnection();
            //启动连接
            connection.start();
            //创建会话
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //通过会话创建目标
            Destination dest = session.createQueue(subject);
            //创建mq消息的消费者
            MessageConsumer consumer = session.createConsumer(dest);
            //初始化MessageListener
            SyncConsumer me = new SyncConsumer();
            //给消费者设定监听对象
            consumer.setMessageListener(me);

            TimeUnit.MICROSECONDS.sleep(500);// 等待获取消息...

//            List<Object> list = me.getMessages();
//            return list.stream().map(message -> JSON.parseObject((String)message, InvokedMethod.class)).collect(Collectors.toList());
            return me.getMessages();
        } catch (JMSException e) {
            LOGGER.error("【activeMq连接异常】", e);
        } catch (InterruptedException e) {
            e.printStackTrace();
            LOGGER.error("【时钟等待异常】", e);
        } finally {
            try {
                if (connection != null) {
                    connection.stop();
                    connection.close();
                }
            } catch (JMSException ex) {
                ex.printStackTrace();
                LOGGER.error("【activeMq连接关闭异常】", ex);
            }
        }
        return null;
    }

    static class SyncConsumer implements MessageListener {

        private static final Logger LOGGER = LoggerFactory.getLogger(SyncConsumer.class);
        public List<Object> messages = new ArrayList<>();

        @Override
        public void onMessage(Message message) {
            TextMessage txtMessage = (TextMessage) message;
            try {
                messages.add(txtMessage.getText());
            } catch (JMSException e) {
                LOGGER.error("【监听mq数据异常】", e);
            }
        }

        public List<Object> getMessages() {
            return messages;
        }
    }
}
